Skip to content

Add JitteredCronTimetable for deterministic schedule jitter#69705

Open
Pebble32 wants to merge 3 commits into
apache:mainfrom
Pebble32:add-jittered-cron-timetable
Open

Add JitteredCronTimetable for deterministic schedule jitter#69705
Pebble32 wants to merge 3 commits into
apache:mainfrom
Pebble32:add-jittered-cron-timetable

Conversation

@Pebble32

Copy link
Copy Markdown

Add JitteredCronTimetable, an opt-in CronTriggerTimetable subclass that shifts each DAG's fire time by a deterministic, per-DAG offset drawn from [0, max_jitter). This spreads out DAGs that share a cron expression so they no longer all fire at the same instant, without changing logical_date / data_interval semantics.

Why

@daily expands to 0 0 * * *, so every daily DAG in a deployment is scheduled at exactly midnight. In large deployments this "thundering herd" at the cron boundary overloads the scheduler and workers — enough to cause task failures when dozens of DAGs are born at the same instant.

The existing ways to deal with this don't actually de-collide the schedule:

Existing option Why it doesn't solve the problem
Hand-pick a unique minute per DAG Manual, doesn't scale, drifts and re-collides as DAG count grows, and throws away the @daily intent
Hash the DAG id into a literal cron string Same loss of intent; not reusable across DAGs/teams; every author re-implements it ad hoc
Pools / concurrency limits (parallelism, max_active_tasks_per_dag, pool slots) These limit or queue execution — the runs are still scheduled at the same instant. They cap contention downstream but never spread the fire times apart at the source.

JitteredCronTimetable is the only approach that moves the fire times themselves, deterministically: the same seed (e.g. the DAG id) always maps to the same offset, so runs stay stable and predictable across scheduler restarts and timetable serialization. Motivated by the discussion in #69027.

What

  • New JitteredCronTimetable(CronTriggerTimetable) in both the Task SDK (author-facing, attrs-based) and airflow-core (scheduler-side), plus the serialization wiring (BUILTIN_TIMETABLES mapping, serialize/deserialize, encode/decode across the SDK↔core boundary).
  • Two extra kw-only params on top of CronTriggerTimetable: seed: str and max_jitter: timedelta.
  • The offset is md5(seed) % max_jitter.total_seconds(), applied as a "strip → cron → apply" coordinate shift so cron/DST alignment is fully delegated to the parent and only the wall-clock fire time is shifted.
  • Fully opt-in and safe by default: with the defaults (seed="", max_jitter=timedelta(0)) the offset is zero and it behaves identically to CronTriggerTimetable. Nothing changes for anyone who doesn't use it.

Tests

airflow-core/tests/unit/timetables/test_jittered_cron_timetable.py, modeled on the existing test_trigger_timetable.py:

  • jittered runs equal base cron runs shifted by the fixed offset, across a catchup sequence including a DST spring-forward (America/New_York);
  • zero max_jitter reproduces CronTriggerTimetable exactly (catchup on/off);
  • offsets are deterministic for a given seed, bounded to [0, max_jitter), and spread across distinct seeds;
  • serialize/deserialize round-trips seed + window + derived offset;
  • full encode → decode round-trip across the SDK/core layers rebuilds the core class.

Was generative AI tooling used to co-author this PR?
  • Yes (please specify the tool below)

Generated-by: Claude (Claude Code), following the guidelines


related: #69027

@boring-cyborg

boring-cyborg Bot commented Jul 10, 2026

Copy link
Copy Markdown

Congratulations on your first Pull Request and welcome to the Apache Airflow community! If you have any issues or are unsure about any anything please check our Contributors' Guide
Here are some useful points:

  • Pay attention to the quality of your code (ruff, mypy and type annotations). Our prek-hooks will help you with that.
  • In case of a new feature add useful documentation (in docstrings or in docs/ directory). Adding a new operator? Check this short guide Consider adding an example Dag that shows how users should use it.
  • Consider using Breeze environment for testing locally, it's a heavy docker but it ships with a working Airflow and a lot of integrations.
  • Be patient and persistent. It might take some time to get a review or get the final approval from Committers.
  • Please follow ASF Code of Conduct for all communication including (but not limited to) comments on Pull Requests, Mailing list and Slack.
  • Be sure to read the Airflow Coding style.
  • Always keep your Pull Requests rebased, otherwise your build might fail due to changes not related to your commits.
    Apache Airflow is a community-driven project and together we are making it better 🚀.
    In case of doubts contact the developers at:
    Mailing List: dev@airflow.apache.org
    Slack: https://s.apache.org/airflow-slack

Pebble32 added 3 commits July 20, 2026 14:07
Signed-off-by: Adam <111773160+Pebble32@users.noreply.github.com>
Signed-off-by: Adam <111773160+Pebble32@users.noreply.github.com>
Signed-off-by: Adam <111773160+Pebble32@users.noreply.github.com>
@Pebble32
Pebble32 force-pushed the add-jittered-cron-timetable branch from 5f777d1 to b668d8d Compare July 20, 2026 14:08
super().__init__(cron, timezone=timezone, interval=interval, run_immediately=run_immediately)
h = int(hashlib.md5(seed.encode()).hexdigest(), 16)
self._offset = (
datetime.timedelta(seconds=h % int(max_jitter.total_seconds()))

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The guard is max_jitter > timedelta(0) but the divisor is int(max_jitter.total_seconds()), so any 0 < max_jitter < 1s passes the guard and then hits modulo by zero. max_jitter=timedelta(milliseconds=500) raises ZeroDivisionError here at construction. The int() also silently drops sub-second precision, so timedelta(seconds=1.5) truncates to a 1s window and the offset can never exceed it. Flooring the guard at 1s, or dropping the int() truncation, closes both.

max_jitter: datetime.timedelta,
) -> None:
super().__init__(cron, timezone=timezone, interval=interval, run_immediately=run_immediately)
h = int(hashlib.md5(seed.encode()).hexdigest(), 16)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

hashlib.md5(seed.encode()) called directly raises on FIPS-enabled Python builds. The hash here isn't security-sensitive, so airflow.utils.hashlib_wrapper.md5 (which passes usedforsecurity=False) keeps it working on FIPS, the same way serialized_dag.py and dagcode.py already do. This runs scheduler-side on every deserialize, so on a FIPS build every DAG using this timetable would fail to load.

sharing one minute still beats every DAG firing at once).

All ``data_interval`` and ``logical_date`` semantics are inherited from
``CronTriggerTimetable`` -- only the wall-clock fire time is shifted.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

"Only the wall-clock fire time is shifted" reads as if logical_date stays pinned to the cron boundary, but it doesn't. With the default interval=0, next_dagrun_info returns DagRunInfo.interval(next_start_time, next_start_time) where next_start_time is the jittered time, so logical_date (= data_interval.start) moves by the offset too. The max_jitter caveat further down ("the shift cannot push a run's logical_date across a day or period boundary") already assumes this, so the two statements contradict each other. Worth rewording to say the offset shifts logical_date/data_interval as well, or deciding whether logical_date should stay pinned to the boundary.

``run_immediately``.
"""

seed: str = attrs.field(kw_only=True, default="")

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

With seed defaulting to "", a user who sets max_jitter but forgets seed gets the same md5("") offset for every DAG, so they all fire at the same shifted instant -- the herd just moves off the cron boundary instead of spreading out, silently defeating the point of the feature. The no-op default only makes sense when max_jitter=0 too. Could this raise (or warn) when max_jitter > 0 and seed == ""? Note the core __init__ already makes seed required, so the two classes disagree on this today.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants